const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { pool } = require('./config/db'); 
const path = require('path');
const fs = require('fs');
const { authenticateToken } = require('./middleware/auth');
const auth = require('./middleware/auth'); // 添加这一行，引入auth中间件
const adminCoursesRouter = require('./routes/admin-courses');
console.log('正在加载管理员成绩路由模块...');
const adminGradesRouter = require('./routes/admin-grades'); // 引入管理员成绩路由
console.log('管理员成绩路由模块加载完成');

const app = express();

// 中间件
app.use(cors());
app.use(express.json());
app.use(morgan('dev'));

// 添加请求日志中间件 - 增强版
app.use((req, res, next) => {
  console.log(`收到请求: ${req.method} ${req.path}`);
  console.log(`请求头: ${JSON.stringify(req.headers)}`);
  
  // 特别关注成绩模板下载请求
  if (req.path.includes('/api/admin/grades/template')) {
    console.log('检测到成绩模板下载请求，详细信息:');
    console.log(`- 完整URL: ${req.protocol}://${req.get('host')}${req.originalUrl}`);
    console.log(`- 请求方法: ${req.method}`);
    console.log(`- 请求参数: ${JSON.stringify(req.query)}`);
    console.log(`- 请求体: ${JSON.stringify(req.body)}`);
    console.log(`- 用户代理: ${req.get('user-agent')}`);
  }
  
  // 捕获响应完成事件
  res.on('finish', () => {
    console.log(`响应完成: ${req.method} ${req.path} - 状态码: ${res.statusCode}`);
    if (req.path.includes('/api/admin/grades/template')) {
      console.log(`成绩模板下载请求响应状态码: ${res.statusCode}`);
    }
  });
  
  next();
});

// 检查routes目录是否存在
const routesDir = path.join(__dirname, 'routes');
if (!fs.existsSync(routesDir)) {
  console.error('routes目录不存在!');
} else {
  console.log('routes目录存在，路径:', routesDir);
  
  // 列出routes目录中的文件
  const files = fs.readdirSync(routesDir);
  console.log('routes目录中的文件:', files);
}

// 引入路由模块
console.log('开始引入路由模块...');
const authRouter = require('./routes/auth');
const usersRouter = require('./routes/users');
const attendanceRouter = require('./routes/attendance'); 
const examsRouter = require('./routes/exams');
const scoresRouter = require('./routes/scores');
const noticesRouter = require('./routes/notices');
const logsRouter = require('./routes/logs');
const debugRouter = require('./routes/debug');
const testRouter = require('./routes/test');
const gradesRoutes = require('./routes/grades');
// 引入新的路由文件
const teacherIndexRouter = require('./routes/teacher-index');
const teacherAttendanceRouter = require('./routes/teacherAttendance'); // 新增教师考勤路由
const coursesRouter = require('./routes/courses');
const departmentsRouter = require('./routes/departments');
const classesRouter = require('./routes/classes');
const messagesRouter = require('./routes/messages');
const systemRouter = require('./routes/system');
const userRoutes = require('./routes/user');
const adminRoutes = require('./routes/admin');
const adminLeaveRoutes = require('./routes/admin-leave'); // 请假管理路由
// const attendanceRoutes = require('./routes/attendance'); // 注释掉重复引入
const leavesRouter = require('./routes/leaves'); // 学生请假路由
const adminTimetableRouter = require('./routes/admin-timetable');
const adminCopyRouter = require('./routes/admin-copy'); // 引入课表复制路由
console.log('正在加载成绩分析路由模块...');
const adminGradesAnalysisRouter = require('./routes/admin-grades-analysis');
console.log('成绩分析路由模块加载完成');
const adminNoticesRouter = require('./routes/admin-notices');
// 添加调试路由 - 移到路由注册之前
app.get('/api/debug/routes', (req, res) => {
  const routes = [];
  
  // 获取所有注册的路由
  app._router.stack.forEach(middleware => {
    if (middleware.route) {
      // 直接注册的路由
      routes.push({
        path: middleware.route.path,
        methods: Object.keys(middleware.route.methods)
      });
    } else if (middleware.name === 'router') {
      // 通过 app.use 注册的路由
      middleware.handle.stack.forEach(handler => {
        if (handler.route) {
          const path = middleware.regexp.toString()
            .replace('\\^', '')
            .replace('\\/?(?=\\/|$)', '')
            .replace(/\\\//g, '/');
          
          routes.push({
            path: path + handler.route.path,
            methods: Object.keys(handler.route.methods)
          });
        }
      });
    }
  });
  
  res.json(routes);
});


// 保留直接模板下载路由，确保功能正常
app.get('/api/admin/grades/template-direct', async (req, res) => {
  console.log('直接模板下载路由被调用');
  try {
    const Excel = require('exceljs');
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet('成绩导入模板');
    
    // 添加表头
    worksheet.columns = [
      { header: '学号', key: 'studentId', width: 15 },
      { header: '姓名', key: 'studentName', width: 15 },
      { header: '课程编号', key: 'courseId', width: 15 },
      { header: '课程名称', key: 'courseName', width: 20 },
      { header: '学期', key: 'term', width: 15 },
      { header: '成绩', key: 'score', width: 10 }
    ];
    
    // 设置表头样式
    worksheet.getRow(1).font = { bold: true };
    worksheet.getRow(1).alignment = { vertical: 'middle', horizontal: 'center' };
    
    // 添加示例数据
    worksheet.addRow({
      studentId: '2023001',
      studentName: '张三',
      courseId: 'CS101',
      courseName: '计算机基础',
      term: '2023-2024-1',
      score: 85
    });
    
    worksheet.addRow({
      studentId: '2023002',
      studentName: '李四',
      courseId: 'CS101',
      courseName: '计算机基础',
      term: '2023-2024-1',
      score: 92
    });
    
    // 添加说明
    worksheet.addRow({});
    worksheet.addRow({studentId: '说明：请按照以上格式填写成绩数据，然后上传'});
    
    // 设置响应头 - 修复中文文件名编码问题
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    // 使用英文文件名避免编码问题
    res.setHeader('Content-Disposition', 'attachment; filename=grades_template.xlsx');
    
    // 将Excel文件写入响应
    await workbook.xlsx.write(res);
    res.end();
    
  } catch (error) {
    console.error('测试模板下载错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 注册路由
console.log('开始注册路由...');
app.use('/api/auth', authRouter);
app.use('/api/users', usersRouter);
app.use('/api/attendance', attendanceRouter); // 使用统一的考勤路由
app.use('/api/exams', examsRouter);
app.use('/api/scores', scoresRouter);
app.use('/api/notices', noticesRouter);
app.use('/api/logs', logsRouter);
app.use('/api/debug', debugRouter);
app.use('/api/test', testRouter);
app.use('/api/courses', coursesRouter);
app.use('/api/departments', departmentsRouter);
app.use('/api/classes', classesRouter);
app.use('/api/grades', gradesRoutes);
app.use('/api/messages', messagesRouter);
app.use('/api/system', systemRouter);
app.use('/api/admin', adminRoutes);
app.use('/api/admin/courses', adminCoursesRouter);
app.use('/api/admin/leaves', adminLeaveRoutes); // 注册管理员请假管理路由
app.use('/api/leaves', leavesRouter); // 学生请假路由
app.use('/api/admin/timetable/copy', adminCopyRouter); // 注册课表复制路由
app.use('/api/admin/timetable', adminTimetableRouter);
app.use('/api/admin/grades/analysis', adminGradesAnalysisRouter);
app.use('/api/admin/grades', adminGradesRouter);
app.use('/api/admin/notices', adminNoticesRouter);

// 教师相关路由 - 确保这些路由在最后注册，避免路径冲突
console.log('注册教师路由...');
app.use('/api/teacher', teacherIndexRouter);
app.use('/api/teacher', teacherAttendanceRouter);

// 删除所有重复的路由注册
// 以下代码应该被删除
// app.use('/api/courses', coursesRouter);
// app.use('/api/departments', departmentsRouter);
// app.use('/api/classes', classesRouter);
// app.use('/api/grades', gradesRoutes);
// app.use('/api/messages', messagesRouter);
// app.use('/api/system', systemRouter);
// app.use('/api/admin', adminRoutes);
// app.use('/api/admin/courses', adminCoursesRouter);
// app.use('/api/admin/leaves', adminLeaveRoutes);
// app.use('/api/attendance', attendanceRoutes);
// app.use('/api/leaves', leavesRouter);
// app.use('/api/admin/timetable/copy', adminCopyRouter);
// app.use('/api/admin/timetable', adminTimetableRouter);
// app.use('/api/admin/grades/analysis', adminGradesAnalysisRouter);
// app.use('/api/teacher', teacherAttendanceRouter);
// app.use('/api/admin/grades', adminGradesRouter);
// app.use('/api/admin/notices', adminNoticesRouter);

app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use((err, req, res, next) => {
  console.error('服务器错误:', err.stack);
  res.status(500).json({ message: '服务器错误', error: err.message });
});
console.log('所有路由注册完成');
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});


module.exports = app;
